package middleware

import (
	"context"
	"fmt"
	"github.com/cloudwego/hertz/pkg/app"
)

func ResponseHeader(c context.Context, ctx *app.RequestContext) {
	ctx.Next(c)
	setHeader(ctx)
}

func setHeader(ctx *app.RequestContext) {
	ctx.Response.Header.Set("Access-Control-Allow-Credentials", "true")
	ctx.Response.Header.Set("Access-Control-Allow-Headers", "Origin,Content-Type,Accept,User-Agent,Cookie,Authorization,X-Auth-Token,X-Requested-With,authorization")
	ctx.Response.Header.Set("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE")
	ctx.Response.Header.Set("Access-Control-Max-Age", "3628800")
	origin := string(ctx.GetHeader("Origin"))
	if origin == "" {
		uri := ctx.GetRequest().URI()
		origin = fmt.Sprintf("%s:%s", string(uri.Scheme()), string(uri.Path()))
	}
	ctx.Response.Header.Set("Access-Control-Allow-Origin", origin)
}
